package com.logistics.sequence.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logistics.sequence.entity.domain.Sequence;
import com.logistics.sequence.mapper.SequenceMapper;
import com.logistics.utils.tool.StringUtils;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;

@Service
public class SequenceService extends ServiceImpl<SequenceMapper, Sequence> {


    /**
     * 获取编码
     * @param ruleName
     * @return
     */
    public Integer getCode(String ruleName){
        int val = 1;
        synchronized (ruleName){
            Sequence result = this.getOne(new LambdaQueryWrapper<Sequence>().
                    eq(Sequence::getName, ruleName));
            if(StringUtils.isNotNull(result)){
                val = result.getCurrentValue() + 1;
                result.setCurrentValue(val);
                this.update(result, new LambdaQueryWrapper<Sequence>().eq(Sequence::getName, ruleName));
            } else {
                this.save(Sequence.build(ruleName, val));
            }
        }
        return val;
    }


    /**
     * 获取编码
     * @param ruleName
     * @param digit
     * @return
     */
    public String getCode(String ruleName, int digit){
        NumberFormat formatter = NumberFormat.getNumberInstance();
        formatter.setMinimumIntegerDigits(digit);
        formatter.setGroupingUsed(false);
        return formatter.format(this.getCode(ruleName));
    }

}
